const { addAddress, updateAddress, getAddressById } = require('../../../../services/address/address');
const districtsData = require('../../../../assets/districts');
const addressManager = require('../../../../model/address');
 
Page({
  data: {
    multiArray: [[], []], // 三级选择器数据：省、市、区
    multiIndex: [0, 0], // 当前选择的省、市、区索引
    keys: [[], []],
    mode: 'add', // 模式：add 或 edit
    addressId: null,
    address: {
      receiverName: '',
      phoneNumber: '',
      state: '',
      city: '',
      district: '',
      addressLine1: '',
      postalCode: '',
      isDefault: false,
    },
  },

  onLoad(options) {
    const { addressId } = options;
    this.setData({
      mode: addressId ? 'edit' : 'add',
      addressId,
    });

    this.initializeRegionList();
    if (options.addressId) {
      this.fetchAddressDetails(options.addressId);
    }
  },

  // 初始化省市数据
  initializeRegionList() {
    const provinces = Object.entries(districtsData['00']); // 省份键值对
    const firstProvinceKey = provinces[0][0]; // 第一个省的键
    const cities = Object.entries(districtsData[firstProvinceKey]); // 第一个省对应的城市键值对

    this.setData({
      multiArray: [
        provinces.map(([_, name]) => name), // 显示省名
        cities.map(([_, name]) => name), // 显示市名
      ],
      keys: [
        provinces.map(([key]) => key), // 省键
        cities.map(([key]) => key), // 市键
      ],
    });
  },

  // 处理 Picker 的列变化
  handleColumnChange(e) {
    const { column, value } = e.detail;
    const { keys, multiArray } = this.data;

    if (column === 0) {
      // 当省改变时，更新市列表
      const selectedProvinceKey = keys[0][value];
      const cities = Object.entries(districtsData[selectedProvinceKey]);

      this.setData({
        'multiArray[1]': cities.map(([_, name]) => name), // 更新市
        'keys[1]': cities.map(([key]) => key),
        'multiIndex[0]': value,
        'multiIndex[1]': 0,
      });
    } else if (column === 1) {
      this.setData({
        'multiIndex[1]': value,
      });
    }
  },

  // 处理 Picker 的值变化
  handleRegionChange(e) {
    const { value } = e.detail;
    const { multiArray } = this.data;

    this.setData({
      multiIndex: value,
      address: {
        ...this.data.address,
        state: multiArray[0][value[0]], // 省
        city: multiArray[1][value[1]], // 市
      },
    });
  },

  // 获取编辑模式下的地址详情
  async fetchAddressDetails(addressId) {
    const address = await getAddressById(addressId);

    const provinceKey = Object.entries(districtsData['00']).find(([_, name]) => name === address.state)[0];
    const cities = Object.entries(districtsData[provinceKey]);
    const cityKey = cities.find(([_, name]) => name === address.city)[0];

    this.setData({
      multiIndex: [
        Object.keys(districtsData['00']).indexOf(provinceKey),
        Object.keys(districtsData[provinceKey]).indexOf(cityKey),
      ],
      'multiArray[1]': cities.map(([_, name]) => name),
      'keys[1]': cities.map(([key]) => key),
      address,
    });
  },

  handleDistrictInput(e) {
    const { value } = e.detail;
    this.setData({
      address: {
        ...this.data.address,
        district: value,
      },
    });
  },

  handleInputChange(e) {
    const { field } = e.currentTarget.dataset;
    const { value } = e.detail;
    this.setData({
      address: {
        ...this.data.address,
        [field]: value,
      },
    });
  },


  toggleDefault() {
    this.setData({
      'address.isDefault': !this.data.address.isDefault,
    });
  },

  async handleSubmit() {
    const { address } = this.data;
  
    // 验证字段是否填写完整
    const requiredFields = [
      { field: 'receiverName', label: '收货人' },
      { field: 'phoneNumber', label: '手机号' },
      { field: 'state', label: '省份' },
      { field: 'city', label: '城市' },
      { field: 'district', label: '区' },
      { field: 'addressLine1', label: '门牌号' },
      { field: 'postalCode', label: '邮编' }
    ];
  
    for (const { field, label } of requiredFields) {
      if (!address[field] || address[field].trim() === '') {
        wx.showToast({
          title: `${label}不能为空`,
          icon: 'none',
        });
        return;
      }
    }
  
    try {
      if (address.isDefault) {
        addressManager.setAllAddressesNonDefault();
      }

      if (this.data.mode === 'add') {
        await addAddress(address);
        wx.showToast({ title: '地址新增成功' });
      } else {
        await updateAddress(this.data.addressId, address);
        wx.showToast({ title: '地址更新成功' });
      }
      wx.navigateBack();
    } catch (error) {
      console.error('Failed to save address:', error);
      wx.showToast({ title: '保存失败', icon: 'none' });
    }
  },
});
